<?php

namespace Core;

/**
 * Description of Langs
 *
 * @author Admin
 */
class Langs
{
	private static $_lang = null;
	
	public static function setLang($lang)
	{
		if(isset(\App::configs()->langs['locales'][$lang]))
		{
			self::$_lang = $lang;
			
			$locale = \App::configs()->langs['locales'][$lang];

			putenv("LANG=".$lang);
			setlocale(LC_ALL, $locale);
			header('Content-Language: '.str_replace('_', '-', $lang));
			
			bindtextdomain('domain', \App::configs()->langs['localesDir']);
			textdomain('domain');
			bind_textdomain_codeset('domain', 'UTF-8');
		}
	}
	
	public static function getLang()
	{
		return self::$_lang;
	}
	
	public static function getBrowserLang()
	{
		if($_SERVER && isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
			return strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
		
		return '';
	}
	
	public static function changeLangUrl($lang)
	{
		$url = 'http://' . $_SERVER['HTTP_HOST'] . '' . $_SERVER['REQUEST_URI'];
		
		if(preg_match("/^\/([a-zA-Z]{2})($|\/)/", $_SERVER['REQUEST_URI']))
		{
			$url =  preg_replace("~\/([a-zA-Z]{2})($|\/)~iu", '/'. $lang .'/', $url);
		}
		else if(!empty($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] != '/')
		{
			$url = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $lang . $_SERVER['REQUEST_URI'];
		}
		
		if(empty($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == '/')
			$url = trim($url, '/') . '/' . $lang . '/';

		return $url;
	}
	
}
